package com.fangwaii.core.executor;

import com.alibaba.fastjson.JSONObject;
import com.fangwaii.core.Type.SimpleTypeRegistry;
import com.fangwaii.core.mapping.HttpStatement;
import com.fangwaii.core.session.Configuration;
import com.fangwaii.core.datasource.Connection;
import com.fangwaii.core.executor.result.ExecutorResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author lxc18
 * @date 2024/12/5 15:43
 * @description BaseExecutor
 */
public class BaseExecutor implements Executor{
    private Logger logger = LoggerFactory.getLogger(BaseExecutor.class);
    protected Configuration configuration;
    protected Connection connection;

    public BaseExecutor(Configuration configuration, Connection connection) {
        this.configuration = configuration;
        this.connection = connection;
    }

    @Override
    public ExecutorResult execute(HttpStatement httpStatement, Map<String, Object> parameter) {
        String methodName = httpStatement.getMethodName();
        //传入的参数类型
        String parameterType = httpStatement.parameterType();
        //传入的参数类型个数
        String[] parameterTypes = new String[1];//只准传一个参数，要么是基本类型或者包装类型，要么是自定义类型
        parameterTypes[0]=parameterType;
        //判断传入的类型是基本类型还是自定义类型
        //如果是基本类型，直接可以使用
        //传入的参数值
        Object[] objectParams = new Object[1]; //1个参数值
        if(SimpleTypeRegistry.isSimpleType(parameterType)){
            for (Map.Entry<String, Object> entry : parameter.entrySet()) {
                objectParams[0]=entry.getValue();
            }

        }
        else{
            //如果是自定义类型，需要使用JSONObject
            JSONObject param= new JSONObject();
            //将parameter转换到param
            for (Map.Entry<String, Object> entry : parameter.entrySet()) {
                param.put(entry.getKey(),entry.getValue());
            }
            objectParams[0]=param;
        }

        try {
            Object data = connection.execute(methodName, parameterTypes, objectParams);
            return ExecutorResult.excutorSucess(data);
        }
        catch (Exception e){
            return ExecutorResult.excutorFail(e);
        }

    }

}
